package com.zxc.thread;

import org.eclipse.swt.widgets.Display;

import com.zxc.database.DataBase;
import com.zxc.service.ConsoleService;
import com.zxc.service.TransDataService;
import com.zxc.service.TransDataThreadService;

public class ReceiveDataRunnable implements Runnable{

	private TransDataThreadService threadService;
	
	private TransDataService service;
	
	private Display display;
	
	private int count = 0;
	
	private int perSize = 0;
	
	public ReceiveDataRunnable(TransDataThreadService threadService){
		this.threadService = threadService;
		this.service = threadService.getService();
	}

	public void run() {

		threadService.calculateCount(TransDataThreadService.THREAD_ADD);
		try {
			while(threadService.isRun){
				perSize = service.receiveData();
				count += perSize;
				if(perSize != DataBase.PER_SIZE){
					break;
				}
			}
		} catch(final Exception e){
			threadService.isRun = false;
			display.asyncExec(new Runnable(){

				public void run() {
					if(display.isDisposed()){
						return;
					}
					ConsoleService.receiveMessage(e.getMessage());
				}
				
			});
		}
		service.addReadCount(count);	
		
		threadService.calculateCount(TransDataThreadService.THREAD_MINUS);
		if(threadService.getCount() <= 0){
			long endTime = System.currentTimeMillis();
			service.setEscapeTime(endTime - service.getStartTime());
			display.asyncExec(new Runnable() {

				public void run() {
					if (display.isDisposed()) {
						return;
					}
					ConsoleService.receiveMessage(service.getEndMessage());
				}

			});
		}
		
		
	}
	
	public int getCount(){
		return count;
	}
	public void setDisplay(Display display) {
		this.display = display;
	}

}
